import React, { useState, useRef, useEffect } from 'react'
import { Avatar, Input, Button, Upload, message, Form, Modal } from 'antd'
import { 
  UserOutlined, 
  PhoneOutlined, 
  MailOutlined, 
  CameraOutlined,
  CloseOutlined,
  EditOutlined,
  SaveOutlined
} from '@ant-design/icons'
import defaultAvatar from '@/assets/images/default-avatar.jpg'
import { getUserInfoService, updateUserInfoService, uploadAvatarService } from '@/api/user'
import { useUserInfo } from '@/context/userInfoContext'
import './index.scss'

function UserCenter({ onClose }) {
  const [form] = Form.useForm()
  const [isEditing, setIsEditing] = useState(false)
  const [avatarUrl, setAvatarUrl] = useState(defaultAvatar)
  const [loading, setLoading] = useState(false)
  const fileInputRef = useRef(null)

  // 使用Context中的用户信息
  const { userInfo, setUserInfo } = useUserInfo()

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      // 调用后端接口
      const res = await getUserInfoService()
      if (res.data) {
        // 更新Context中的用户信息 - 只取data字段
        setUserInfo(res.data.data)
        if (res.data.data.avatar) {
          setAvatarUrl(res.data.data.avatar)
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      message.error('获取用户信息失败')
    }
  }

  // 处理头像上传
  const handleAvatarUpload = async (e) => {
    const file = e.target.files[0]
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        message.error('图片大小不能超过5MB')
        return
      }
      
      try {
        const formData = new FormData()
        formData.append('avatar', file)
        // 调用后端接口
        const response = await uploadAvatarService(formData)
        // 如果上传成功，则设置头像
        if (response.data?.avatarUrl) {
          setAvatarUrl(response.data.avatarUrl)
          // 更新Context中用户信息的头像字段
          setUserInfo(prev => ({
            ...prev,
            avatar: response.data.avatarUrl
          }))
          message.success('头像上传成功')
        }
      } catch (error) {
        console.error('头像上传失败:', error)
        if (error.response?.data?.message) {
          message.error(error.response.data.message)
        } else {
          message.error('头像上传失败')
        }
      }
    }
  }

  // 触发文件选择
  const triggerFileSelect = () => {
    // 模拟点击一个隐藏的 <input type="file" /> 元素，从而触发文件选择对话框弹出
    fileInputRef.current?.click()
  }

  // 保存用户信息
  const handleSaveInfo = async () => {
    try {
      setLoading(true)
      const res = await form.validateFields()
      
      // 调用API保存用户信息
      const updateData = {
        username: res.username,
        email: res.email
      }
      
      // 只有当手机号不为空时才添加到更新数据中
      if (res.phone && res.phone.trim()) {
        updateData.phone = res.phone.trim()
      }
      
      const response = await updateUserInfoService(updateData)
      
      // 更新Context中的用户信息
      if (response.data) {
        setUserInfo(response.data.data)
        if (response.data.data.avatar) {
          setAvatarUrl(response.data.data.avatar)
        }
      }
      
      setIsEditing(false)
      message.success('保存成功')
    } catch (error) {
      console.error('保存失败:', error)
      if (error.response?.data?.message) {
        message.error(error.response.data.message)
      } else {
        message.error('保存失败，请重试')
      }
    } finally {
      setLoading(false)
    }
  }

  // 取消编辑
  const handleCancel = () => {
    setIsEditing(false)
    // 重置表单为当前用户信息，而不是初始值
    form.setFieldsValue(userInfo)
  }

  // 组件加载时获取用户信息（如果Context中没有用户信息）
  useEffect(() => {
    if (!userInfo.username) {
      fetchUserInfo()
    } else {
      // 如果Context中已有用户信息，直接使用
      if (userInfo.avatar) {
        setAvatarUrl(userInfo.avatar)
      }
    }
  }, [userInfo.username])

  // 当userInfo更新时，同步更新表单值
  useEffect(() => {
    if (userInfo.username) {
      form.setFieldsValue(userInfo)
    }
  }, [userInfo, form])

  return (
    <div className='user-center' onClick={(e) => e.stopPropagation()}>
      <div className='user-container'>
        {/* 头部 */}
        <div className='header'>
          <div className='title'>
            <span>个人中心</span>
          </div>
          <div className='close-btn' onClick={onClose}>
            <CloseOutlined />
          </div>
        </div>

        {/* 内容区域 */}
        <div className='content'>
          <Form
            key={userInfo.userId} // 使用userId作为key，强制重新渲染
            form={form}
            layout="vertical"
            initialValues={userInfo}
            className="user-form"
          >
            {/* 头像区域 */}
            <div className='avatar-section'>
              <div className='avatar-container'>
                <Avatar 
                  size={120} 
                  src={avatarUrl}
                  icon={<UserOutlined />}
                />
                <div className='avatar-upload' onClick={triggerFileSelect}>
                  <CameraOutlined />
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  style={{ display: 'none' }}
                  onChange={handleAvatarUpload}
                />
              </div>
              <div className='avatar-tip'>点击相机图标更换头像</div>
            </div>

            {/* 用户信息表单 */}
            <div className='info-section'>
              <div className='info-item'>
                <div className='info-label'>
                  <UserOutlined />
                  <span>用户名</span>
                </div>
                {isEditing ? (
                  <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                    <Input placeholder="请输入用户名" />
                  </Form.Item>
                ) : (
                  <div className='info-value'>{userInfo.username}</div>
                )}
              </div>

              <div className='info-item'>
                <div className='info-label'>
                  <UserOutlined />
                  <span>用户ID</span>
                </div>
                <div className='info-value readonly'>{userInfo.userId}</div>
              </div>

              <div className='info-item'>
                <div className='info-label'>
                  <PhoneOutlined />
                  <span>手机号码</span>
                </div>
                {isEditing ? (
                  <Form.Item name="phone" rules={[
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                  ]}>
                    <Input placeholder="请输入手机号码（可选）" />
                  </Form.Item>
                ) : (
                  <div className='info-value'>{userInfo.phone || '未设置'}</div>
                )}
              </div>

              <div className='info-item'>
                <div className='info-label'>
                  <MailOutlined />
                  <span>邮箱地址</span>
                </div>
                {isEditing ? (
                  <Form.Item name="email" rules={[
                    { required: true, message: '请输入邮箱地址' },
                    { type: 'email', message: '请输入正确的邮箱地址' }
                  ]}>
                    <Input placeholder="请输入邮箱地址" />
                  </Form.Item>
                ) : (
                  <div className='info-value'>{userInfo.email}</div>
                )}
              </div>
            </div>

            {/* 操作按钮 */}
            <div className='action-section'>
              {isEditing ? (
                <div className='action-buttons'>
                  <Button onClick={handleCancel} className='cancel-btn'>
                    取消
                  </Button>
                  <Button 
                    type="primary" 
                    onClick={handleSaveInfo}
                    loading={loading}
                    className='save-btn'
                  >
                    <SaveOutlined />
                    保存
                  </Button>
                </div>
              ) : (
                <Button 
                  type="primary" 
                  onClick={() => setIsEditing(true)}
                  className='edit-btn'
                >
                  <EditOutlined />
                  编辑信息
                </Button>
              )}
            </div>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default UserCenter